<!DOCTYPE html>
          <head>
        <meta charset="utf-8">
            
            <title>
                「Android-SQLite」0x02从加载本地数据库开始 | ttdevs
            </title>
            <meta content="width=device-width, initial-scale=1" name="viewport">
            <meta name="theme-color" content="#4184f3">
            
            
            <link href="/favicon.ico" rel="icon"/>
            

            <link rel="stylesheet" href="/css/highlight.light.css">
            <link rel="stylesheet" href="/css/prism-customize.css">
            <link rel="stylesheet" href="/css/nav-icon.css">
            <link rel="stylesheet" href="/css/waves.min.css">
            <link rel="stylesheet" href="/css/jquery.tocify.css">
            <link rel="stylesheet" href="/css/main.css">
            <link rel="stylesheet" href="/css/nav-indicator.css">
            
  

  
  <!-- 谷歌统计 -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-97465173-1', 'auto');
    ga('send', 'pageview');

  </script>
  
            </meta>
        </meta>
    </head>

    <body>
        <header>
            <!-- cover image or sth. -->
        </header>
        <div id="main" class="m-scene">
            
<div class="nav-wrapper">

    <div class="container">
        <nav>
            <div class="logo wave">
                <a href="/" id="logo">
                    ttdevs
                </a>
            </div>
            <div class="nav-toggle-icon" >
                <div class="material-hamburger">
                    <span>
                    </span>
                    <span>
                    </span>
                    <span>
                    </span>
                </div>
            </div>
            <div class="menu-wrapper">
                <div class="nav-indicator">
                </div>
                <ul class="menus">
                    
                     
                        <li>
                            <a class="wave " href="/">
                                首页
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/archives">
                                归档
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/about">
                                关于
                            </a>
                        </li>
                     
                    
                   
                </ul>
            </div>
        </nav>
    </div>
</div>
            <div class="container content">
                <div class="scene_element scene_element--fadein">
                    <div class="row">
    <div class="main">
        <article>
          
          <header class="post-header with-cover" style="background-image:url('/1970/01/01/[Android-SQLite]0x02从加载本地数据库开始/cover.jpg')" >
          
          </header>
          <h1 class="post-title">「Android-SQLite」0x02从加载本地数据库开始</h1>

          <section class="post-info">
            <span class="post-date">1970/01/01</span>
            
            <span class="post-category">
                <a class="article-category-link" href="/categories/技术/">技术</a>
            </span>
            
            
            <span class="post-tags">
              <ul class="post-tag-list"><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/Android/">Android</a></li><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/SQLite/">SQLite</a></li></ul>
            </span>
            
          </section>

          <section class="post-content">
            <h2 id="0x00-引言"><a href="/1970/01/01/[Android-SQLite]0x02从加载本地数据库开始/#0x00-引言" class="headerlink" title="0x00 引言"></a>0x00 引言</h2><blockquote>
<p>好久以前就写了，但是一直拖拖拉拉的，在草稿箱里放了两个星期还没写完，想想这样托下去又要废掉了，还是分开来吧，写多少是多少。</p>
</blockquote>
<p>Android的SQLite数据库简单使用一段时间了，现在想抽些时间总结下，不然总感觉很乱。</p>
<h2 id="0x01-SQLiteExpert"><a href="/1970/01/01/[Android-SQLite]0x02从加载本地数据库开始/#0x01-SQLiteExpert" class="headerlink" title="0x01 SQLiteExpert"></a>0x01 SQLiteExpert</h2><p>先说一个工具，<code>SQLite Expert</code>，一款SQLite数据库管理工具，下载地址： <a href="http://www.sqliteexpert.com/" target="_blank" rel="external">http://www.sqliteexpert.com/</a>，Personal Edition是免费的，日常使用基本足够，需要专业版的可以自行网上找寻。当然，其他免费的工具还有很多，如：<code>SQLite Database Browser</code>、 <code>SQLiteManager</code> 等。<br><img src="http://img.blog.csdn.net/20130916222611000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdHRkZXZz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt=""></p>
<h2 id="0x02-加载本地数据库"><a href="/1970/01/01/[Android-SQLite]0x02从加载本地数据库开始/#0x02-加载本地数据库" class="headerlink" title="0x02 加载本地数据库"></a>0x02 加载本地数据库</h2><p>假设我们SDCard的根目录上已经存在一个数据库，名称为：ChinaCity.db。这时候我们可以这样操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">readDataBaseFromSDCard</span><span class="params">()</span> </span>&#123;</div><div class="line">    String dbPath = Environment.getExternalStorageDirectory() + <span class="string">"/ChinaCity.db"</span>;</div><div class="line"></div><div class="line">    File dbFile = <span class="keyword">new</span> File(dbPath);</div><div class="line">    <span class="keyword">if</span> (!dbFile.exists()) &#123;</div><div class="line">        Toast.makeText(getApplicationContext(), <span class="string">"请先点击拷贝到SDCard"</span>, Toast.LENGTH_LONG).show();</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    openOrCreateDatabase(dbPath, SQLiteDatabase.CREATE_IF_NECESSARY, <span class="keyword">null</span>);</div><div class="line"></div><div class="line">    SQLiteDatabase db = SQLiteDatabase.openDatabase(dbPath, <span class="keyword">null</span>, SQLiteDatabase.OPEN_READWRITE);</div><div class="line">    <span class="comment">// db = openOrCreateDatabase(dbPath, SQLiteDatabase.OPEN_READWRITE, null);</span></div><div class="line"></div><div class="line">    StringBuffer sb = <span class="keyword">new</span> StringBuffer();</div><div class="line">    Cursor cursor = db.rawQuery(<span class="string">"select * from china_provinces_code"</span>, <span class="keyword">null</span>);</div><div class="line">    <span class="keyword">while</span> (cursor.moveToNext()) &#123;</div><div class="line">        <span class="keyword">int</span> id = cursor.getInt(cursor.getColumnIndex(<span class="string">"_id"</span>));</div><div class="line">        String name = cursor.getString(cursor.getColumnIndex(<span class="string">"name"</span>));</div><div class="line">        sb.append(id + <span class="string">":"</span> + name + <span class="string">" \n"</span>);</div><div class="line">    &#125;</div><div class="line">    System.out.println(sb.toString());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>先用SQLiteDatabase的一个静态方法openDatabase打开一个数据库，第一个参数为数据库文件路径，第二个参数一般为null，第三个参数为打开数据库的方式，由于只需要读取数据，所以我们选择 <code>SQLiteDatabase.OPEN_READONLY</code>，此种方式的好处是数据库存在的话就不会出错；另外一种为 <code>SQLiteDatabase.OPEN_READWRITE</code>，以读写的方式打开。执行上面代码，我们会看与上图信息相同的：</p>
<p><img src="http://img.blog.csdn.net/20130916225300890?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdHRkZXZz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">  </p>
<p>开发的时候，我们可能会需要一些初始化数据，比如城市代码信息，这样我们就可以事先创建好一个数据库，写入初始数据，将其放入自己的apk中一起分发。这个时候我们就可以直接从资源文件中读取这个数据库文件写入到应用的数据库目录或者SDCard中，然后就可以对其操作，拷贝可以这样操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * 拷贝资源中数据库</div><div class="line"> *</div><div class="line"> * <span class="doctag">@param</span> where 1SDCARD,2LOCAL</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">copyDataBase</span><span class="params">(<span class="keyword">int</span> where)</span> </span>&#123;</div><div class="line">    <span class="comment">// 每个应用都有一个数据库目录，他位于 /data/data/packagename/databases/目录下</span></div><div class="line">    String packageName = <span class="string">"com.ttdevs.citydata"</span>; <span class="comment">// xml中配置的</span></div><div class="line">    String dbName = <span class="string">"ChinaCity.db"</span>;</div><div class="line">    String dbPath = <span class="keyword">null</span>;</div><div class="line">    <span class="keyword">if</span> (where == <span class="number">1</span>) &#123; <span class="comment">// sdcard</span></div><div class="line">        dbPath = Environment.getExternalStorageDirectory() + File.separator + dbName;</div><div class="line">    &#125; <span class="keyword">else</span> &#123; <span class="comment">// local, TODO Environment.getDataDirectory()</span></div><div class="line">        dbPath = <span class="string">"/data/data/"</span> + packageName + <span class="string">"/databases/"</span> + dbName;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (where == <span class="number">2</span>) &#123;</div><div class="line">        <span class="keyword">new</span> File(<span class="string">"/data/data/"</span> + packageName + <span class="string">"/databases/"</span>).mkdirs();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (where == <span class="number">1</span> &amp;&amp; !Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) &#123;</div><div class="line">        <span class="keyword">return</span>; <span class="comment">// 未挂载外部存储，拷贝到内部不用判断</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    File dbFile = <span class="keyword">new</span> File(dbPath);</div><div class="line">    <span class="keyword">if</span> (dbFile.exists()) &#123;</div><div class="line">        dbFile.delete();</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        dbFile.createNewFile();</div><div class="line">    &#125; <span class="keyword">catch</span> (IOException e1) &#123;</div><div class="line">        e1.printStackTrace();</div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        InputStream is = getResources().getAssets().open(dbName);</div><div class="line">        OutputStream os = <span class="keyword">new</span> FileOutputStream(dbPath);</div><div class="line"></div><div class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">        <span class="keyword">int</span> length = <span class="number">0</span>;</div><div class="line">        <span class="keyword">while</span> ((length = is.read(buffer)) &gt; <span class="number">0</span>) &#123;</div><div class="line">            os.write(buffer, <span class="number">0</span>, length);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        os.flush();</div><div class="line">        os.close();</div><div class="line">        is.close();</div><div class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">        e.printStackTrace();</div><div class="line">    &#125;</div><div class="line">    Toast.makeText(getApplicationContext(), <span class="string">"拷贝成功"</span>, Toast.LENGTH_LONG).show();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>代码不是很严谨，凑活着看哈。经过以上步骤，我们就可以开始使用数据库，数据库的常用操作，在接下来的介绍中继续。</p>
<h2 id="0x03-下载"><a href="/1970/01/01/[Android-SQLite]0x02从加载本地数据库开始/#0x03-下载" class="headerlink" title="0x03 下载"></a>0x03 下载</h2><p>ChinaCity.db数据库： <a href="http://download.csdn.net/detail/ttdevs/6332431" target="_blank" rel="external">下载</a></p>
<p><img src="https://raw.githubusercontent.com/ttdevs/ttdevs.github.io/common/images/logo.png" alt="Create by ttdevs"></p>

          </section>
        </article>
        

       
        <div class="pager">
          
            <a class="post-prev pager-item" href="/1970/01/01/[Android-Bluetooth]0x01操作/" >
              <strong class="article-nav-caption">上一篇</strong>
              <p class="post-nav-title">「Android-Bluetooth」0x01操作</p>
            </a>
          
          
            <a class="post-next pager-item" href="/1970/01/01/[Android-SQLite]0x01创建自己的数据库/">
              <strong class="article-nav-caption">下一篇</strong>
              <p class="post-nav-title">「Android-SQLite」0x01创建自己的数据库</p>
            </a>
          
        </div>
        

         <!-- comments -->
        <div class="comment-section">
  
    


</div>

    </div>
    
    <aside>
        <div id="toc">
        </div>
    </aside>
    
</div>

                </div>
            </div>
        </div>
        <footer class="footer">
    <p>由<a href="http://hexo.io/" target="_blank">Hexo</a>强力驱动，搭载<a href="https://github.com/wayou/hexo-theme-gstyle">gstyle</a>主题</p>
    <p>
        &copy; 2017 ttdevs
    </p>
</footer>
<script src="/lib/jquery.js"></script>
<script src="/lib/waves.js"></script>
<script src="/lib/jquery-ui.js"></script>
<script src="/lib/jquery.tocify.js"></script>
<script src="/js/main.js"></script>

    </body>
</html>
